package cn.edu.sdjzu.usercenter.service.impl;
import java.util.Date;


import cn.edu.sdjzu.usercenter.common.ErrorCode;
import cn.edu.sdjzu.usercenter.exception.BusinessException;
import cn.edu.sdjzu.usercenter.mapper.UserMapper;
import cn.edu.sdjzu.usercenter.model.User;
import cn.edu.sdjzu.usercenter.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static cn.edu.sdjzu.usercenter.contant.UserContant.USER_LOGIN_STATE;

/**
* @author lili
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-03-27 18:53:41
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值：混淆密码
     */
    private static final String  SALT = "liu";



    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword,String planetCode) {

        //1.校验
        //如果给定的一组字符串中所有字符串都为空白或为 null，
        // 那么 StringUtils.isAllBlank 方法将返回 true；否则，返回 false。
        if(StringUtils.isAllBlank(userAccount,userPassword,checkPassword,planetCode)){
            // todo 修改为自定义异常
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");

        }
        if(userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户帐号小于4位");
        }
        if(planetCode.length() >5 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码小于8位");

        }
        if(userPassword.length()<8 || checkPassword.length() <8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编号过长");
        }

        //账户不能包含特字符
        //定义正则表达式，允许字母、数字、下划线，不允许特殊字符
        String validPattern = "^[a-zA-Z0-9_]+$";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(!matcher.find()){
            return -1;
        }


        //密码和校验密码相同
        if(!userPassword.equals(checkPassword)){
            return -1;

        }

        //账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
//        long count = this.count(queryWrapper);
        Long count = userMapper.selectCount(queryWrapper);
        if(count>0){
            return -1;
        }

        //星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode",planetCode);
//        long count = this.count(queryWrapper);
        count = userMapper.selectCount(queryWrapper);
        if(count>0){
            return -1;
        }


        //2.加密
        String encryptedPassword = DigestUtils.md5DigestAsHex((SALT+ userPassword).getBytes());


        //3.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptedPassword);

        boolean saveResult = this.save(user);
        if(!saveResult) {
            return -1;
        }

        return user.getId();
    }


    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验

        if(StringUtils.isAllBlank(userAccount,userPassword)){
            return null;

        }
        if(userAccount.length() < 4){
            return null;
        }
        if(userPassword.length()<8){
            return null;
        }

        //账户不能包含特字符
        //定义正则表达式，允许字母、数字、下划线，不允许特殊字符
        String validPattern = "^[a-zA-Z0-9_]+$";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if(!matcher.find()){
            return null;
        }


        //2.加密

        String encryptedPassword = DigestUtils.md5DigestAsHex((SALT+ userPassword).getBytes());

        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encryptedPassword);
        User user = userMapper.selectOne(queryWrapper);
        //用户不存在
        if(user ==null){
            log.info("user login faild , userAccount cannot match userPassword");
            return null;
        }

        //3.用户脱敏
        User safeUser = getSafetyUser(user);

        //4.记录用户登录状态
        request.getSession().setAttribute(USER_LOGIN_STATE,user);
        return safeUser;

    }

    /**
     * 用户脱敏
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser){
        if(originUser == null){
            return null;
        }

        User safeUser = new User();
        safeUser.setId(originUser.getId());
        safeUser.setUsername(originUser.getUsername());
        safeUser.setUserAccount(originUser.getUserAccount());
        safeUser.setAvatarUrl(originUser.getAvatarUrl());
        safeUser.setGender(originUser.getGender());
        safeUser.setPhone(originUser.getPhone());
        safeUser.setPlanetCode(originUser.getPlanetCode());
        safeUser.setUserRole(originUser.getUserRole());
        safeUser.setEmail(originUser.getEmail());
        safeUser.setUserStatus(originUser.getUserStatus());
        safeUser.setCreateTime(new Date());
        return safeUser;

    }

    /**
     * 用户注销
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }


}




